package sdf

import (
	"BlendSDF/sdf/init_matrix"
	"BlendSDF/sdf/load"
	"BlendSDF/sdf/sdf"
	"fmt"
	"image/png"
	"os"
	"sync"
)

var wg sync.WaitGroup

func GetSDF(address string) ([][]float64, error) {
	//加载png图片
	length, width, img, err := load.LoadPhoto(address)
	if err != nil {
		return nil, err
	}
	//获取遮罩和初始化矩阵
	var masks [][]bool
	var m [][]*init_matrix.Point
	wg.Add(2)
	go func(masks *[][]bool, err error) {
		defer wg.Done()
		*masks, err = init_matrix.GetPhotoMask(img, length, width, 0.5)
		if err != nil {
			*masks = nil
		}
	}(&masks, err)

	go func(m *[][]*init_matrix.Point, err error) {
		defer wg.Done()
		*m = init_matrix.InitMatrix(length, width)
	}(&m, err)
	wg.Wait()
	if masks == nil {
		return nil, fmt.Errorf("masks is nil")
	}

	res := sdf.GenerateSDF(length, width, m, masks)
	if res == nil {
		return nil, fmt.Errorf("sdf is nil")
	}
	return res, nil
}

func GetLengthAndWidth(address string) (length, width int, err error) {
	file, err := os.Open(address)
	if err != nil {
		return 0, 0, err
	}
	defer file.Close()

	img, err := png.Decode(file)
	if err != nil {
		return 0, 0, err
	}
	return img.Bounds().Dx(), img.Bounds().Dy(), nil
}
